package com.remac.framework.mybatisplus.extensions.config;

import com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration;
import com.remac.framework.mybatisplus.extensions.context.MybatisPlusExtensionsContext;
import com.remac.framework.mybatisplus.extensions.enhance.IMybatisPlusEnhancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

/**
 * @author Ye Junhui
 * @since 2024/4/24
 */
@Configuration
@AutoConfigureAfter(MybatisPlusAutoConfiguration.class)
@Slf4j
public class MybatisPlusExtensionsAfterLoadAutoConfiguration {

    private final List<IMybatisPlusEnhancer> mybatisPlusEnhancerList;

    private final MybatisPlusExtensionsContext mybatisPlusExtensionsContext;

    public MybatisPlusExtensionsAfterLoadAutoConfiguration(
            MybatisPlusExtensionsContext mybatisPlusExtensionsContext,
            List<IMybatisPlusEnhancer> mybatisPlusEnhancerList
    ) {
        this.mybatisPlusExtensionsContext = mybatisPlusExtensionsContext;
        this.mybatisPlusEnhancerList = mybatisPlusEnhancerList;
        this.doEnhance();
    }

    /**
     * 执行增强
     */
    private void doEnhance(){
        if (!CollectionUtils.isEmpty(this.mybatisPlusEnhancerList)){
            log.info("MybatisPlusEnhancer detected ,begin enhancing !!!");
        }
        if (Objects.nonNull(mybatisPlusExtensionsContext.getMybatisConfiguration())) {
            this.mybatisPlusEnhancerList.forEach(mybatisPlusEnhancer -> {
                log.info("MybatisPlusEnhancer , {} do enhance",mybatisPlusEnhancer.getClass().getName());
                mybatisPlusEnhancer.enhance(mybatisPlusExtensionsContext.getMybatisConfiguration());
            });
        }
    }
}
